package blue_bridge_cup_learning.前缀和;

public class 二维前缀和模板 {
    public static void main(String[] args) {
        int[][] arr = new int[][] {
                { 1, 7, 2, 4 },
                { 3, 5, 2, 8 },
                { 2, 1, 2, 3 }
        };
        System.out.println("原数组：");
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[0].length; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println("--------------------------------");
        int[][] preSum = new int[arr.length + 1][arr[0].length + 1];
        for (int i = 1; i < preSum.length; i++) {
            for (int j = 1; j < preSum[0].length; j++) {
                System.out.print(preSum[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println("--------------------------------");
        int[][] preSum2 = getPreSum(arr);
        for (int i = 1; i < preSum2.length; i++) {
            for (int j = 1; j < preSum2[0].length; j++) {
                System.out.print(preSum2[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static int[][] getPreSum(int[][] arr) {
        int[][] preSum = new int[arr.length + 1][arr[0].length + 1];
        for (int i = 1; i < arr.length + 1; i++) {
            for (int j = 1; j < arr[0].length + 1; j++) {
                preSum[i][j] = preSum[i - 1][j] + preSum[i][j - 1] - preSum[i - 1][j - 1] + arr[i - 1][j - 1];
            }
        }
        return preSum;
    }

}
